
module spi_delay(
    input                           clk_i,
    input                           rstn_i,

    input [31:0]                    delay_cnt_i,    // 特定时间需要的时钟个数
    input                           start_i,        // 脉冲

    output reg                      flag_o          // 定时结束脉冲
);

reg [31:0]                          cnt;
reg                                 cnt_incr;

wire                                cnt_flag;
assign cnt_flag = (cnt == delay_cnt_i - 1) ? 1'b1 : 1'b0;

always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        cnt_incr <= 1'b0;
    end
    else if (cnt_flag)begin
        cnt_incr <= 1'b0;
    end
    else if (start_i)begin
        cnt_incr <= 1'b1;
    end
end

always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        cnt <= 'd0;
    end
    else if (cnt_flag)begin
        cnt <= 'd0;
    end
    else if (cnt_incr | start_i)begin
        cnt <= cnt + 1'b1;
    end
    else begin
        cnt <= 'd0;
    end
end

always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        flag_o <= 1'b0;
    end
    else begin
        flag_o <= cnt_flag;
    end
end
endmodule